package cn.lingyangwl.agile.common.security.aspect;

import cn.lingyangwl.agile.common.security.annotation.DataRule;
import cn.lingyangwl.agile.common.security.model.DataRuleGenerator;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据过滤处理
 * 
 * @author shenguangyang
 */
@Slf4j
@Aspect
@Component
public class DataRuleAspect {

    // 配置织入点
    @Pointcut("@annotation(cn.lingyangwl.agile.common.security.annotation.DataRule)")
    public void dataRulePointCut() {
    }

    @Before("dataRulePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        handleDataRule(point);
    }
    protected void handleDataRule(final JoinPoint joinPoint) {
        // 获得注解
        DataRule dataRule = getAnnotationLog(joinPoint);
        if (dataRule == null) {
            return;
        }
        DataRuleGenerator.initSqlCondition(dataRule.entityClass(), dataRule.code());
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataRule getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataRule.class);
        }
        return null;
    }

}
